<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Http;
use App\Models\User;

class WechatLoginController extends Controller
{
    /**
     * 重定向到微信扫码登录页面
     */
    public function redirectToWechat()
    {
        $appId = 'wx1ff04de8b254879e'; //env('WECHAT_APPID');
        $redirectUri = urlencode(env('WECHAT_REDIRECT_URI'));
        $scope = 'snsapi_login'; // 扫码登录固定作用域

        // 生成微信授权链接
        $wechatAuthUrl = "https://open.weixin.qq.com/connect/qrconnect?appid={$appId}&redirect_uri={$redirectUri}&response_type=code&scope={$scope}&state=STATE#wechat_redirect";

        return redirect()->away($wechatAuthUrl);
    }

    /**
     * 处理微信回调
     */
    public function handleWechatCallback(Request $request)
    {
        $code = $request->query('code');
        if (!$code) {
            return redirect()->route('login')->withErrors('微信授权失败');
        }

        try {
            // 1. 使用code获取access_token和openid
            $tokenResponse = Http::get('https://api.weixin.qq.com/sns/oauth2/access_token', [
                'appid' => 'wx1ff04de8b254879e',//env('WECHAT_APPID'),
                'secret' => '2f7995457fe54403ecbd8ecc1837d316',//env('WECHAT_APPSECRET'),
                'code' => $code,
                'grant_type' => 'authorization_code',
            ])->json();

            if (isset($tokenResponse['errcode'])) {
                throw new \Exception('获取access_token失败: ' . $tokenResponse['errmsg']);
            }

            // 2. 使用access_token和openid获取用户信息
            $userInfoResponse = Http::get('https://api.weixin.qq.com/sns/userinfo', [
                'access_token' => $tokenResponse['access_token'],
                'openid' => $tokenResponse['openid'],
                'lang' => 'zh_CN',
            ])->json();

            if (isset($userInfoResponse['errcode'])) {
                throw new \Exception('获取用户信息失败: ' . $userInfoResponse['errmsg']);
            }

            // 3. 查找或创建用户
            $user = User::firstOrCreate(
                ['openid' => $userInfoResponse['openid']],
                [
                    'name' => $userInfoResponse['nickname'],
                    'avatar' => $userInfoResponse['headimgurl'],
                    'password' => bcrypt(uniqid()), // 随机密码，不影响微信登录
                ]
            );

            // 4. 登录用户
            Auth::login($user);

            // 5. 重定向到首页
            return redirect()->route('home');

        } catch (\Exception $e) {
            return redirect()->route('login')->withErrors('登录失败: ' . $e->getMessage());
        }
    }
}
